$(document).ready(function () {
    var table = $('table#table').DataTable({
        initComplete: function(settings, json) {
            $("#table").removeClass('dataTable');
            $("#table").parent().addClass('table-responsive');

            $("#table").parent()
              .css('max-height', $(window).height() - $('#query-area').height() - 260)
              .css('height', 'auto')
              .css('overflow-y', 'visible');

            $("#table").on('change', 'input[type="checkbox"]', function () {
                if($(this).prop('checked')) {
                    $(this).closest('tr').addClass('warning');
                } else {
                    $(this).closest('tr').removeClass('warning');
                }
            });

            // 动态添加搜索条件行间距样式
        $('<style>').text(`#query-area .form-group {margin-bottom: 15px;}`).appendTo('head');

        // 动态添加表头居中样式
        $('<style>').text('#table thead th { text-align: center !important; }').appendTo('head');

        // 添加行点击事件处理
            $("#table tbody").on('click', 'tr', function(e) {
                // 避免点击复选框本身时触发两次
                if (!$(e.target).is('input[type="checkbox"]')) {
                    // 找到当前行的复选框
                    var checkbox = $(this).find('input[type="checkbox"]').first();
                    // 切换复选框状态
                    checkbox.prop('checked', !checkbox.prop('checked'));
                    // 触发change事件以更新行样式
                    checkbox.trigger('change');
                }
            });
        },
        ajax: {
            url: baseUrl + '/datatable',
            data : function(d) {
                var no       = $('.search-form').find('input[name="documentNumber"]').val();
                var type     = $('.search-form').find('select#type').val();
                var status   = $('.search-form').find('select#status').val();
                //var material = $('.search-form').find('select#material').val();
                var material        = $('.search-form').find('input[name="material"]').val();
                var containernum    = $('.search-form').find('input[name="containernum"]').val();
                var deliverystatus  = $('.search-form').find('select#deliverystatus').val();

                var finfromdate     = $('.search-form').find('input[name="finfromdate"]').val();
                var fintodate       = $('.search-form').find('input[name="fintodate"]').val();
                var bindfromdate    = $('.search-form').find('input[name="bindfromdate"]').val();
                var bindtodate      = $('.search-form').find('input[name="bindtodate"]').val();

                d.category             = 'SM';
                d.no                   = no;
                d.type                 = type;
                d.status               = status;
                d.material             = material;
                d.deliverycontainernum = containernum;
                d.deliverystatus       = deliverystatus;
                d.finfromdate          = finfromdate;
                d.fintodate            = fintodate;
                d.bindfromdate         = bindfromdate;
                d.bindtodate           = bindtodate;
                return d;
            }
        },
        order: [
            [9, 'desc']
        ],
        columns: [{
            data: 'id',
            sortable: false,
            defaultContent: '',
            'class': 'text-center',
            render: function (data, type, row, meta) {
                return '<input type="checkbox" name="ids" value="' + data + '" style="transform: scale(1.5);"/>'
            }


        },{
            'class': 'text-center',
            name: 'documentNumber',
            data: 'documentNumber',
            render: function (data, type, row, meta) {
                return `<a hfre="#" style="text-decoration: underline" onclick="showAsndetail(${row.id})">${row.documentNumber}</a>`;
            }
        },{
            'class': 'text-center',
            name: 'deliveryContainerNum',
            data: 'deliveryContainerNum'
        },{
            'class': 'text-center',
            name: 'deliveryLastStatus',
            data: 'deliveryLastStatus',
            render: function (data, type, row, meta) {
                /*if ((data==null) || (data=='')) return '码盘中';
                 if (data=='0000') return '码盘中';
                 if (data=='0150') return '码盘中';
                 if (data=='0210') return '上架中';
                 if (data=='0880') return '完成';
                 if (data=='0850') return '取消';*/
                if ((data==null) || (data=='')) return '创建单据';
                if (data=='0000') return '创建单据';
                if (data=='0150') return '创建单据';
                if (data=='0210') return '开始入库';
                if (data=='0250') return '入库完成';
                if (data=='0300') return '入库完成';
                if (data=='0880') return '入库完成';
                if (data=='0850') return '组盘取消';
            }
        },{
            'class': 'text-center',
            name: 'notes',
            data: 'notes'
        },{
            'class': 'text-center',
            name: 'createdBy',
            data: 'createdBy',
            render: function (data, type, row, meta) {
                if (data =='admin') {
                    return '管理员';
                }
                return data;
            }
        },{
            'class': 'text-center',
            name: 'hEdi09',
            data: 'hEdi09'
        },{
            'class': 'text-center',
            name: 'lastModifiedDate',
            data: 'lastModifiedDate'
        },{
            'class': 'text-center',
            name: 'createdDate',
            data: 'createdDate'
        },{
            data: "id",
            defaultContent: '',
            sortable: false,
            'class': 'text-center',
            render: function (data, type, row, meta) {
                //return '<a class="btn btn-default btn-xs" href="'+rootUrl+'/inbound/asndetails/'+ row.id + '"><i class="fa fa-list"></i></a>';
                return `<button type="button" class="btn btn-default btn-xs" onclick="showSmasndetail(${row.id})"><i class="fa fa-list"></i></button>`;
            }
        }, {
            data: "id",
            defaultContent: '',
            sortable: false,
            'class': 'text-center',
            render: function (data, type, row, meta) {
                return ('<div class="btn-group">' +
                '<a  class="btn btn-default btn-xs" title="修改" href="' + baseUrl + '/edit/' + row.id + '"><i class="fa fa-edit"></i></a>' +
                '<a class="btn btn-default btn-xs del" title="删除" href="#"><i class="fa fa-trash-o"></i></a>' +
                '</div>' +
                '&nbsp;&nbsp;');
            }
        }]
    });

    table.on('click', '.del', function () {
        var id = table.row($(this).parents('tr')).data().id;
        $("#delForm #ids").val(id);
        if (id) {
            bootbox.confirm("确定要删除数据吗?", function (result) {
                if (result) {
                    $("#delForm").submit();
                }
            });
        }
    });
    $(".btn.delAll").on("click", function (e) {
        var ids = [];
        $('#table>tbody input:checked').each(function (i, item) {
            ids.push($(item).val());
        });
        $("#delForm #ids").val(ids.join(","));
        if (ids.length > 0) {
            bootbox.confirm("确定要删除选中的数据吗?", function (result) {
                if (result) {
                    $("#delForm").submit();
                }
            });
        } else {
            bootbox.alert("请选择要删除的数据.");
        }
    });

    $(".btn.recvAll").on("click", function (e) {
        var ids = [];
        $('#table>tbody input:checked').each(function (i, item) {
            ids.push($(item).val());
        });
        $("#receiveForm #ids").val(ids.join(","));
        if (ids.length > 0) {
            bootbox.confirm("确定要对选中的单证进行整单收货吗?", function (result) {
                if (result) {
                    $("#receiveForm").submit();
                }
            });
        } else {
            bootbox.alert("请选择要收货的单证.");
        }
    });

    $(".btn.printLabel").on("click", function (e) {
        var ids = [];
        $('#table>tbody input:checked').each(function (i, item) {
            ids.push($(item).val());
        });
        $("#printlabelForm #ids").val(ids.join(","));
        if (ids.length > 0) {
            bootbox.confirm("确定要对选中的单证进行打印吗?", function (result) {
                if (result) {
                    $("#printlabelForm").submit();
                }
            });
        } else {
            bootbox.alert("请选择要打印的单证.");
        }
    });

    $(".btn.closeAll").on("click", function (e) {
        var ids = [];
        $('#table>tbody input:checked').each(function (i, item) {
            ids.push($(item).val());
        });
        $("#closeForm #ids").val(ids.join(","));
        if (ids.length > 0) {
            bootbox.confirm("确定要关闭选中的数据吗?", function (result) {
                if (result) {
                    $("#closeForm").submit();
                }
            });
        } else {
            bootbox.alert("请选择要关闭的数据.");
        }
    });


    table.on('click', '.enable', function () {
        var that = this;
        var data = table.row($(this).parents('tr')).data();
        var id = data.id;
        var enabled = data.enabled;
        bootbox.confirm("确定要更新选中的数据吗?", function(resul) {
            if (resul) {
                $.get(baseUrl + "/enable", {
                    enabled: !enabled,
                    ids: id
                }, function (res) {
                    if (res) {
                        data.enabled = !enabled;
                        $(that).find("i").removeClass("fa-" + (enabled ? "check-" : "") + "square-o").addClass("fa-" + (!enabled ? "check-" : "") + "square-o");
                        toastr.info('操作成功!');
                    }

                });
            }});
    });


    $('.form_datetime').datetimepicker({
        format: 'yyyy-mm-dd',
        weekStart: 1,
        autoclose: true,
        startView: 2,
        minView: 2,
        forceParse: false,
        language: 'cn',
        calendarWeeks: true,
        pickerPosition: "bottom-left"
    }).on('changeDate', function (ev) {
        daycount = 0;
        if (null != ev.date && undefined != ev.date) {
            var day = new Date(ev.date.getYear(), ev.date.getMonth(),ev.date.getDate());
            daycount = day.getDate();
        }

    });

    $('.search-form').on("submit", function (e) {
        table.draw();
        //阻止表单submit
        return false;
    });

});

function showSmasndetail(_id) {
    console.log(_id);
    var $modal = $("#smasnDetailModal");
    $modal.find("iframe").attr("src", `${rootUrl}/inbound/smasndetails/${_id}`);
    $modal.modal('show');
}
